package com.system.util;

import com.alibaba.fastjson2.JSON;
import com.system.constant.CommonConst;
import com.system.entity.mail.MailRecord;
import com.system.service.mail.MailRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class MailUtil {

    /**
     * 1. 来源人名
     * 2. 来源内容
     */
    public static final String originalText = "<hr style=\"border: 1px dashed #ef859d2e;margin: 20px 0\">\n" +
            "            <div>\n" +
            "                <div style=\"font-size: 18px;font-weight: bold;color: #C5343E\">\n" +
            "                    %s\n" +
            "                </div>\n" +
            "                <div style=\"margin-top: 6px;font-size: 16px;color: #000000\">\n" +
            "                    <p>\n" +
            "                        %s\n" +
            "                    </p>\n" +
            "                </div>\n" +
            "            </div>";

    /**
     * 1. 网站名称
     * 2. 邮件类型
     * 3. 发件人
     * 4. 发件内容
     * 5. originalText
     * 6. 网站名称
     */
    public static final String mailText = "<div style=\"font-family: serif;line-height: 22px;padding: 30px\">\n" +
            "    <div style=\"display: flex;justify-content: center;width: 100%%;max-width: 900px;background-image: url('" + CommonConst.DOWNLOAD_URL + "webBackgroundImage/Sara11667042705239112');background-size: cover;border-radius: 10px\"></div>\n" +
            "    <div style=\"margin-top: 20px;display: flex;flex-direction: column;align-items: center\">\n" +
            "        <div style=\"margin: 10px auto 20px;text-align: center\">\n" +
            "            <div style=\"line-height: 32px;font-size: 26px;font-weight: bold;color: #000000\">\n" +
            "                嘿！你在 %s 中收到一条新消息。\n" +
            "            </div>\n" +
            "            <div style=\"font-size: 16px;font-weight: bold;color: rgba(0, 0, 0, 0.19);margin-top: 21px\">\n" +
            "                %s\n" +
            "            </div>\n" +
            "        </div>\n" +
            "        <div style=\"min-width: 250px;max-width: 800px;min-height: 128px;background: #F7F7F7;border-radius: 10px;padding: 32px\">\n" +
            "            <div>\n" +
            "                <div style=\"font-size: 18px;font-weight: bold;color: #C5343E\">\n" +
            "                    %s\n" +
            "                </div>\n" +
            "                <div style=\"margin-top: 6px;font-size: 16px;color: #000000\">\n" +
            "                    <p>\n" +
            "                        %s\n" +
            "                    </p>\n" +
            "                </div>\n" +
            "            </div>\n" +
            "            %s\n" +
            "            <a style=\"width: 150px;height: 38px;background: #ef859d38;border-radius: 32px;display: flex;align-items: center;justify-content: center;text-decoration: none;margin: 40px auto 0\"\n" +
            "               href=\"https://poetize.cn\" target=\"_blank\">\n" +
            "                <span style=\"color: #DB214B\">有朋自远方来</span>\n" +
            "            </a>\n" +
            "        </div>\n" +
            "        <div style=\"margin-top: 20px;font-size: 12px;color: #00000045\">\n" +
            "            此邮件由 %s 自动发出，直接回复无效（一天最多发送 " + CommonConst.COMMENT_IM_MAIL_COUNT + " 条通知邮件），退订请联系站长。\n" +
            "        </div>\n" +
            "    </div>\n" +
            "</div>";

    /**
     * 发件人
     */
    public static final String replyMail = "你之前的评论收到来自 %s 的回复";
    public static final String commentMail = "你的文章 %s 收到来自 %s 的评论";
    public static final String messageMail = "你收到来自 %s 的留言";
    public static final String loveMail = "你收到来自 %s 的祝福";
    public static final String imMail = "你收到来自 %s 的消息";

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Autowired
    private MailRecordService mailRecordService;

    /**
     * 发送邮件，以html的形式
     *
     * @param to      收件人，只能一个
     * @param subject 主题
     * @param text    邮件内容
     */
    @Async
    public void sendMailMessageHtml(String to, String subject, String text) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MailRecord mailRecord = new MailRecord();
        try {
            //先将邮件内容存起来，不需要解析
            mailRecord.setContent(text);
            mailRecord.setSubject(subject);
            mailRecord.setRecipientsMail(to);
            mailRecord.setStatus(CommonConst.STATUS_SUCCESS);
            /**
             * 1、MimeMessageHelper是Spring Framework提供的一个用于发送MIME邮件的帮助类，它可以方便地设置邮件的各种属性
             * 2、第二个参数true表示这个MimeMessage对象是一个多部分消息，即包含附件。
             */
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

            //发送邮箱以及发送人
            messageHelper.setFrom(sendMailer, CommonConst.SITE_NAME);

            //主题
            messageHelper.setSubject(subject);

            //接收人邮箱，可以发送多个
            messageHelper.setTo(to);

            //使用正则 获取text中的所有图片地址
            String regex = "<img.*?src=\"(.*?)\".*?>";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);
            //将图片地址存储起来
            ArrayList<String> urlList = new ArrayList<>();
            int i = 1;
            while (matcher.find()) {
                String imgUrl = matcher.group(1);
                //将图片地址替换成邮件的展示格式 cid:name
                text = text.replace(imgUrl, "cid:mail_" + i);
                urlList.add(imgUrl);
                i++;
            }
            log.info("text :{}", text);

            //发送的内容，为html
            messageHelper.setText(text, true);

            //设置图片
            for (int j = 0; j < urlList.size(); j++) {
                String imgUrl = dowmMailImage(urlList.get(j));
                FileSystemResource fileSystemResource = new FileSystemResource(imgUrl);
                //显示文中的图片：cid:name，name对应的图片
                messageHelper.addInline("mail_" + (j + 1), fileSystemResource);
            }
            //邮件发送时间
            messageHelper.setSentDate(new Date());

            //发送邮件
            mailSender.send(mimeMessage);
            log.info("邮件发送成功！");
        } catch (MessagingException e) {
            mailRecord.setStatus(CommonConst.STATUS_ERROR);
            mailRecord.setContent("错误！");
            log.error("邮件发送失败！");
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            mailRecord.setStatus(CommonConst.STATUS_ERROR);
            mailRecord.setContent("错误！");
            log.error("邮件发送失败！");
            throw new RuntimeException(e);
        }finally {
            mailRecordService.saveMailRecord(mailRecord);
        }
    }

    /**
     * 下载图片到本地
     * @param imageUrl
     * @return
     */
    public String dowmMailImage(String imageUrl) {
        String[] split = imageUrl.split("/");
        int index = split.length-1;
        String imageName = split[index];

        String localFilePath = "resources/smMail/image/";
        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            File file = new File(localFilePath);
            if(!file.exists()){
                file.mkdirs();
                log.info("【文件创建成功！】");
            }
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            inputStream = connection.getInputStream();

            byte[] buffer = new byte[1024];
            int length = 0;
            outputStream = new FileOutputStream(localFilePath+""+imageName);
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        } catch (IOException e) {
            log.error("图片解析失败:{}",e.getMessage());
        } finally {
            try {
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return localFilePath+""+imageName;
    }

    @Async
    public void sendMailMessage(List<String> to, String subject, String text) {
        log.info("发送邮件===================");
        log.info("to：{}", JSON.toJSONString(to));
        log.info("subject：{}", subject);
        log.info("text：{}", text);
        try {
            //true代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人1或多个
            mimeMessageHelper.setTo(to.toArray(new String[0]));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text, true);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            mailSender.send(mimeMessageHelper.getMimeMessage());

            log.info("发送成功==================");
        } catch (MessagingException e) {
            log.info("发送失败==================");
            log.error(e.getMessage());
        }
    }
}
